package net.neptech.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import net.neptech.model.dto.NodeDataDto;
import net.neptech.enums.workflow.InstanceConstant;
import net.neptech.model.dto.node.Node;
import net.neptech.model.workflow.NodeData;
import net.neptech.repository.NodeDataRepo;
import net.neptech.service.NodeDataService;
import net.neptech.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @Author Saya
 * @Date 2025/8/20 12:05
 * @Description TODO
 **/
@Service
public class NodeDataServiceImpl implements NodeDataService {

    @Autowired
    private NodeDataRepo nodeDataRepo;
    /**
     * 保存流程节点数据
     */
    @Override
    public void saveNodeData(NodeDataDto processNodeDataDto) {
        NodeData processNodeData = BeanUtil.copyProperties(processNodeDataDto, NodeData.class);
        nodeDataRepo.save(processNodeData);
    }

    /***
     * 获取节点数据
     * 5s内超过5次调用 升级为热点数据
     */
    @Cacheable(key = "#flowId+'_'+#nodeId", cacheNames = "stringCache")
    @Override
    public String getNodeData(String flowId, String nodeId) {
        //发起人用户任务
        if (StrUtil.startWith(nodeId, InstanceConstant.VariableKey.START_NODE)) {
            nodeId = InstanceConstant.VariableKey.START_NODE;
        }
        NodeData processNodeData = nodeDataRepo.findByFlowIdAndNodeId(flowId, nodeId);
        if (processNodeData == null) {
            throw new RuntimeException("数据不存在");
        }
        return processNodeData.getData();
    }

    /**
     * 返回节点数据
     */
    @Override
    public Node getNode(String flowId, String nodeId) {
        String data = getNodeData(flowId, nodeId);
        return JsonUtil.parseObject(data, Node.class);
    }
}
